import {useEffect, useState} from "react";
import axios from "axios";
import {message} from "antd";


/**
 * 自定义的Hooks函数
 */
function usePublish(publishState) {

    const [dataSource, setDataSource] = useState([]);
    const { username } = JSON.parse(localStorage.getItem('token'));

    useEffect(()=>{
        axios.get(`/api/news?author=${username}&publishState=${publishState}&_expand=category`).then(response=>{
            const data= response.data;
            setDataSource(data)
        });
    }, [username, publishState]);


    // 发布
    const handlePublish= (id)=>{
        setDataSource(dataSource.filter(item=>item.id!==id));
        axios.patch(`/api/news/${id}`, {
            publishState: 1,
            publishTime: Date.now()
        }).then(res=>{
            message.success('您的新闻发布成功')
        })
    }
    // 下线
    const handleSunset= (id)=>{
        setDataSource(dataSource.filter(item=>item.id!==id));
        axios.patch(`/api/news/${id}`, {
            publishState: 2
        }).then(res=>{
            message.success('您的新闻已下线')
        })
    }
    // 删除
    const handleDelete= (id)=>{
        setDataSource(dataSource.filter(item=>item.id!==id));
        axios.delete(`/api/news/${id}`).then(res=>{
            message.success('您的新闻已删除')
        });
    }

    return {
        dataSource,
        handlePublish,
        handleSunset,
        handleDelete
    }
}

export default usePublish;
